// AudioPlug library example
// 2010-05-12 <info@theater4all.nl> http://opensource.org/licenses/mit-license.php
//
// volume setting: 
//        Gain (dB) = 31.5 - (0.5*(255 - N))    where N equals 0-255
//
// serial commands:
//        m1    mute on
//        m0    mute off
//        c1v255   set channel 1 to 255 (+31.5 dB)
//		  c2v192   set channel 2 to 192 (0 dB)
//        c10v0    set channel 10 to 0  (-95.5 dB)
//        s0v255   set channel 0 and 1 to 255 (+31.5 dB)
//	      c0M      set channel 0 to mute (-95.5 dB)
//	      c0=      set channel 0 to 0dB
//        s2=      set channel 2 and 3 to 0dB

#include <AudioPlug.h>

AudioPlug Plug(PORTLOW);

char c;
uint8_t Channel;
uint8_t Value;
bool getChannel = false;
bool getValue = false;
bool stereo = false;

// convert signed float in the range of [ -95,5 to + 35,5 ] to a channel Byte Value
uint8_t dB2Byte (float dBValue)
{
	if (dBValue >= 31.5)
		return 255;
	if (dBValue <= -95.5)
		return 0;
		
	return (uint8_t)(255 + (dBValue - 31.5)*2);
}


// convert a Byte Value to the corresponding dB value
float byte2dB(uint8_t Value)
{
	// calc val to dB
	return (float)(31.5 - ((255 - Value) >> 1)); 
}


void setup()
{
  Serial.begin(57600);
  Serial.println("[AudioPlug test]");
  Plug.addBoard(TWOCHANNELS);
  //Plug.addBoard(TWOCHANNELS);
  //Plug.addBoard(FOURCHANNELS);
  //Plug.addBoard(FOURCHANNELS);
  
  Plug.showChannelMap();
}


void loop()
{
	// Handle commands
	if (Serial.available()) {
		c = Serial.read();
		if ((c == ' ') || (c == '\n'))
			return;		

		switch(c) {
		case 'M':
			Value = 0;
			getValue = true;
			return;
			
		case '=':
			Value = 190;
			getValue = true;
			return;
			
		case 'm':
			while (!Serial.available());
			c = Serial.read();
			if (c == '1') 
				Plug.setMute(MUTEON);
			else 
				Plug.setMute(MUTEOFF);
			return;
			
		
		case 's':	
			stereo = true;
		case 'c':
			Channel = 0;
			getChannel = true;
			getValue = false;
			return;
			
		case 'v':
			Value = 0;
			getValue = true;
			getChannel = false;
			return;
			
		case '\r':
			if (getValue) {
				getValue = false;
				Plug.setVolume(Channel, Value);
				if (stereo) {
					stereo = false;
					Plug.setVolume(Channel+1, Value);
					Serial.print ("Set Stereo channel: ");
				}
				else {
					Serial.print ("Set Channel: ");
				}
				
				// send to plug
				Plug.sendVolumeData();
				Serial.print (Channel, DEC);
				Serial.print (" to ");
				Serial.print (byte2dB(Value));
				Serial.println (" dB");
			}
			return;
		}
		
		if (getChannel) {
			Channel = (Channel * 10) + c - '0';
			return;
		}
		
		if (getValue) {
			Value = (Value * 10) + c - '0';
			return;
		}
	}
}

